import { Injectable } from '@nestjs/common'
import { Repository, Not, IsNull } from 'typeorm'
import { InjectRepository } from '@nestjs/typeorm'
import { CreateAwardDto } from './dto/create-award.dto'
import { UpdateAwardDto } from './dto/update-award.dto'
import { Award } from './entities/award.entity'
import { Staff } from '../staff/entities/staff.entity'
import { AwardRule } from '../award-rule/entities/award-rule.entity'
import { formatDate } from 'src/utils'
@Injectable()
export class AwardService {
  constructor(
    @InjectRepository(Award) private readonly award: Repository<Award>,
    @InjectRepository(Staff) private readonly staff: Repository<Staff>,
    @InjectRepository(AwardRule)
    private readonly awardRule: Repository<AwardRule>
  ) {}
  async create(createAwardDto: CreateAwardDto) {
    const award = new Award()
    const staff = await this.staff.findOne({
      where: { id: createAwardDto.staffId }
    })
    const awardRule = await this.awardRule.findOne({
      where: { id: createAwardDto.awardRuleId }
    })
    award.staff = staff
    award.awardRule = awardRule
    award.desc = createAwardDto.desc
    award.date = formatDate(new Date())
    return this.award.save(award)
  }

  async findAll(
    params: {
      page: number
      pageSize: number
      isDelete?: boolean
    },
    staffId?: number
  ) {
    const where = {}
    params.isDelete && (where['deleteDate'] = Not(IsNull()))
    staffId && (where['staff'] = { id: staffId })
    const data = await this.award.find({
      where: { ...where },
      withDeleted: params.isDelete,
      relations: ['staff', 'awardRule'],
      skip: (params.page - 1) * params.pageSize,
      take: params.pageSize,
      order: { id: 'DESC' }
    })
    const total = await this.award.count({
      where: { ...where },
      relations: ['staff'],
      withDeleted: params.isDelete
    })
    const newData = data.map(item => {
      return {
        ...item,
        staff: {
          id: item.staff.id,
          name: item.staff.name
        },
        awardRule: {
          id: item.awardRule.id,
          name: item.awardRule.name
        }
      }
    })
    return { data: newData, total }
  }

  async update(id: number, updateAwardDto: UpdateAwardDto) {
    const { staffId, awardRuleId, ...rest } = updateAwardDto
    const awardRule = await this.awardRule.findOne({
      where: { id: updateAwardDto.awardRuleId }
    })
    return this.award.update(id, { ...rest, awardRule })
  }

  remove(ids: number[]) {
    return this.award.softDelete(ids)
  }

  restore(ids: number[]) {
    return this.award.restore(ids)
  }
}
